import { io } from "socket.io-client";
import type { Socket } from "socket.io-client";
import { config } from "@/config/config";
import { toView } from "@/utils/utils";
import { userChatListStore, userJoinListStore } from "@/stores/userChatList";
import { addMessageToDB, getLastMessageBySessionID } from "@/Dexie/MessageDB";
import { addUserToDB } from "@/Dexie/UserDB";
import { emitterEmit } from "@/mitt/mitt";
import { sessionIdSelectedFunc } from "@/views/ChatView/Hooks";
import type { Ref } from "vue";
import { newMessageLengthFunc } from "@/components/ChatBox/Hooks";

let socket: Socket;
let reconnectTimer: number = 0;
// 登录初始化数据
export const socketLogin = () => {
  if (socket) socket.disconnect();
  if (!(localStorage["token"] && localStorage["account"] && localStorage["tokenExpireTime"]) || (new Date().getTime() > localStorage["tokenExpireTime"])) {
    ElMessage.error("请重新登录！");
    toView("Login");
    return;
  }
  socket = io(config.SOCKET_URL);
  sendSocketMsg("login", localStorage["account"]);
  socketOnEvent("loginRes", (data: httpResultType) => {
    if (data.code === 400) {
      ElMessage.error(data.errMsg);
      return;
    }
    ElMessage.success(data.msg);
  });
  socketOnEvent("userInfo", (data: httpResultType) => {
    if (data.code === 400) {
      ElMessage.error(data.errMsg);
      return;
    }
    addUserToDB(data.msg);
  });
  socketOnEvent("userChatList", (data: httpResultType) => {
    if (data.code === 400) {
      ElMessage.error(data.errMsg);
      return;
    }
    if (data.msg.count === 0) {
      return;
    }
    const userChatListStoreIns = userChatListStore();
    userChatListStoreIns.setUserChatList(data.msg.rows);
  });
  socketOnEvent("userJoinList", (data: httpResultType) => {
    const getNewMessage = async (list: joinListItemType[]) => {
      for (const item of list) {
        let sessionID = item._session_id;
        let startTime = (await getLastMessageBySessionID(sessionID))?.timestamp || 0;
        sendSocketMsg("getNewMessage", {
          sessionID,
          startTime
        });
      }
    };
    if (data.code === 400) {
      ElMessage.error(data.errMsg);
      return;
    }
    if (data.msg.count === 0) {
      return;
    }
    const userJoinListStoreIns = userJoinListStore();
    userJoinListStoreIns.setUserJoinList(data.msg.rows);
    getNewMessage(data.msg.rows);
  });
  socketOnEvent("messageTo", async (data: httpResultType) => {
    if (data.code === 400) {
      ElMessage.error(data.errMsg);
      return;
    }
    let msg: msgTableItemType = {
      message: data.msg.message,
      sender: data.msg.sender,
      session_id: data.msg.sessionID,
      status: 0,
      timestamp: data.msg.timestamp
    };
    let result = await addMessageToDB(msg);
    if (!result) {
      ElMessage.error("消息保存失败");
      return;
    }
    // 获取选中的对话
    const [getSessionIdSelected] = sessionIdSelectedFunc();
    const sessionIdSelected: Ref<string> = getSessionIdSelected();
    
    if(sessionIdSelected.value === msg.session_id) {
      // 更新当前聊天页面的内容
      emitterEmit(`chatMessage-${msg.session_id}`, [Infinity, true, msg.sender === localStorage["account"]]);
    } else {
      // 添加未读信息 如果不是选中的聊天对象直接+1
      const [getNewMessageLengthObj, setNewMessageLength] = newMessageLengthFunc();
      const newMessageLengthObj = getNewMessageLengthObj();
      setNewMessageLength(msg.session_id, (newMessageLengthObj.value[msg.session_id] || 0) + 1);
    }
    
    //好友列表中的信息
    emitterEmit(`friendCard-${msg.session_id}`);
  });
  socketOnEvent("sendMsgError", (data: httpResultType) => {
    if (data.code === 400) {
      ElMessage.error(data.errMsg);
      return;
    }
  });
  socketOnEvent("connectError", (data: httpResultType) => {
    if (data.code === 400) {
      ElMessage.error(data.errMsg);
      return;
    }
  });
  socketOnEvent("newMessage", async (data: httpResultType) => {
    // 未接收到的消息
    if (data.code === 400) {
      ElMessage.error(data.errMsg);
      return;
    }
    if (data.msg.count === 0) {
      return;
    }
    let list = data.msg.rows;
    list.sort((a:any, b:any) => {
      return Number(a._timestamp) - Number(b._timestamp);
    });
    // 添加信息进入数据库并且通知消息列表内容更新
    for (const item of list) {
      console.log(item, '-----');
      await addMessageToDB({
        message: item._message,
        sender: item._sender,
        session_id: item._session_id,
        status: item._status,
        timestamp: Number(item._timestamp)
      });
      // 获取选中的对话
      const [getSessionIdSelected] = sessionIdSelectedFunc();
      const sessionIdSelected: Ref<string> = getSessionIdSelected();
  
      if(sessionIdSelected.value === item._session_id) {
        // 更新当前聊天页面的内容
        emitterEmit(`chatMessage-${item._session_id}`, [Infinity, true, false]);
      } else {
        // 添加未读信息 如果不是选中的聊天对象直接+1
        const [getNewMessageLengthObj, setNewMessageLength] = newMessageLengthFunc();
        const newMessageLengthObj = getNewMessageLengthObj();
        setNewMessageLength(item._session_id, (newMessageLengthObj.value[item._session_id] || 0) + 1);
      }
      // 发送事件 更新当前聊天页面的内容和好友列表中的信息
      emitterEmit(`friendCard-${item._session_id}`);
    }
  });
  socketOnEvent("disconnect", (data: any) => {
    let instance = ElMessage.error({ message: "与服务器断开连接！", duration: 0 });
    reconnectTimer = setInterval(() => {
      if (socket.connected) {
        sendSocketMsg("login", localStorage["account"]);
        if (localStorage["msgToUser"]) {
          sendSocketMsg("joinRoom", JSON.parse(localStorage["msgToUser"]));
        }
        clearInterval(reconnectTimer);
        instance.close();
      }
    }, 100);
  });
};
// 发送socket信息
export const sendSocketMsg = (type: string, msg: any) => {
  if (!socket) {
    ElMessage.error("请重新登录");
  }
  socket.emit(type, msg);
};
// 监听socket信息
export const socketOnEvent = (type: string, listenEvent: any) => {
  if (!socket) {
    ElMessage.error("请重新登录");
  }
  socket.on(type, listenEvent);
};

